#include "Wiimote.h"
class point {
	public:
	int x;
	int y;

	point( int x, int y ) {
		this->x = x;
		this->y = y;
	}
	int getX() { return this->x; }
	int getY() { return this->y; }
};


class wiiIface : public IPCObject {
	public:

	bool loop;
	Wiimote * wm;

	bool reset;
	bool draw;

	int color;

	point * p;

	int x;
	int y;

	wiiIface() {

		this->p = new point(0,0);

		this->loop = true;

		this->draw = true;
		this->reset = false;

		this->color = 0;

		this->wm = new Wiimote(1, 5);
		wm->copyright();

		std::cout << "\nSearching for discoverable Wiimotes\n";
		bool connected = wm->connect();
		if ( connected ) {
			std::cout << "Wiimote(s) Connected!\n";
		} else {
			std::cout << "Wiimote Search Failure!\n";
		}
	
		for (int i = 0; i < wm->get_connected() ; ++i) {
			wm->toggle_rumble(i);
		}
		usleep(200000);
		for (int i = 0; i < wm->get_connected() ; ++i) {
			wm->toggle_rumble(i);
		}
		for ( int i = 0; i < wm->get_connected() ; ++i ) {
			wm->set_led_bitmask( i, ( i + 1 ) * 2 * 8 );
			wm->enable_ir( i );
		}
	}

	int getWiiX() { return this->p->getX(); }
	int getWiiY() { return this->p->getY(); }

	point getPoint() {
		point pizzle( this->p->getX(), this->p->getY() );
		return pizzle;
	}

	bool shouldReset() {
		if ( this->reset ) {
			this->reset = false;
			return true;
		} else {
			return false;
		}
	}

	bool shouldDraw() { return this->draw; }
	int getColor() { return this->color; }

	void event( int i ) {
		if ( this->wm->one_is_pressed( i ) ) {
			this->reset = true;
		}

		if ( this->wm->b_is_pressed( i ) ) {
			this->draw = false;
		}

		if ( this->wm->a_is_pressed( i ) ) {
			this->draw = true;
		}

		if ( this->wm->plus_is_pressed( i ) ) {
			this->color = 0;
		}
		if ( this->wm->minus_is_pressed( i ) ) {
			this->color = 1;
		}

		this->p = new point(wm->ir_x(i), wm->ir_y(i));

	}
	void run() {
		while ( this->loop && wm->active() ) {
			if ( wm->pending() ) {
				for (int i = 0; i < wm->get_connected() ; ++i) {
					switch ( wm->get_event(i) ) {
						case WIIUSE_EVENT:
							this->event( i );
//							std::cout << "Event\n";
							break;
						case WIIUSE_DISCONNECT:
						case WIIUSE_UNEXPECTED_DISCONNECT:
							/* the wiimote disconnected */
//								this->handle_disconnect( i );
							break;
						default:
							break;
					}
				}
			}
		}
	}
};

void * thread_wiiIface( void * ptr ) {
	wiiIface * wi = static_cast <wiiIface *> (ptr);
	wi->run();
	std::cout << "WiiIFace ending\n";
	void * ret = NULL;
	return ret;
}

